﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QuadRemote.Core
{
    class ConfigDefinition
    {
        public Dictionary<String, List<VarValue>> varValues;

        public ConfigDefinition()
        {
            varValues = new Dictionary<string, List<VarValue>>();
        }

        public Boolean isLoaded()
        {
            return varValues.Count > 0;
        }

        public void incomingConfigValue(CommandIn args)
        {
            if (args.packet[0] == 0x00)
            {
                // end of config!
                //RenderFields();
                return;
            }
            //Console.WriteLine("CONFIG: " + Tools.getHexString(args.packet));

            VarValue newVal = new VarValue();

            int pos = 0;
            String groupName = Tools.bytesToString(args.packet, pos);
            pos += groupName.Length + 1;
            String varName = Tools.bytesToString(args.packet, pos);
            pos += varName.Length + 1;

            newVal.groupName = groupName;

            newVal.name = varName;

            newVal.totalBytes = args.packet[pos++];
            newVal.numValues = args.packet[pos++];
            newVal.intBits = args.packet[pos++];
            newVal.floatBits = args.packet[pos++];
            newVal.valueType = args.packet[pos++];
            newVal.enumValues = new Dictionary<int, String>();

            String enums = Tools.bytesToString(args.packet, pos);
            pos += enums.Length + 1;

            newVal.bytesPerValue = newVal.totalBytes / newVal.numValues;

            if (enums.Length > 0)
            {
                String[] enumArr = enums.Split(new char[] { '|' });

                int enumIndex = 0;
                foreach (String e in enumArr)
                {
                    newVal.enumValues.Add(enumIndex, e);
                    enumIndex++;
                }
                newVal.isEnum = true;
            }

            if (args.packet.Length - pos != newVal.totalBytes)
            {
                Console.WriteLine("Invalid var length " + (args.packet.Length - pos) + "  expected " + newVal.totalBytes);
                return;
            }

            newVal.value = new byte[newVal.totalBytes];

            System.Array.Copy(args.packet, pos, newVal.value, 0, newVal.totalBytes);
            //Console.WriteLine(" -> val: " + Tools.getHexString(newVal.value));

            if (varValues.ContainsKey(groupName))
            {
                varValues[groupName].Add(newVal);
            }
            else
            {
                varValues[groupName] = new List<VarValue>();
                varValues[groupName].Add(newVal);
            }
        }

    }
}
